use common_base::{
    bincode,
    prelude::*,
    serde::{self, Serialize},
    serde_json,
};
use common_core::data::{DataModel, Metadata, RowsetOwner};

#[derive(Debug, Serialize)]
#[serde(crate = "self::serde")]
#[serde(rename_all = "camelCase")]
pub struct MdmDataModel {
    pub(crate) dct_id: String,
    pub(crate) rlgl_id: String,
    pub(crate) fkey_id: String,
    pub(crate) mdl_id: String,
    #[serde(skip)]
    self_rowset: RowsetOwner,
}

impl Default for MdmDataModel {
    fn default() -> Self {
        Self {
            dct_id: Default::default(),
            rlgl_id: Default::default(),
            fkey_id: Default::default(),
            mdl_id: Default::default(),
            self_rowset: Default::default(),
        }
    }
}

impl MdmDataModel {
    pub fn set_value(&mut self, key: &str, value: Metadata) {
        self.self_rowset.put_object(key, value.into())
    }
}

impl DataModel for MdmDataModel {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn into_json_value(&self) -> serde_json::Value {
        serde_json::to_value(self)
            .inspect_err(|e| warn!("can not serialize for {:?}, cause: {}", self, e))
            .unwrap_or(serde_json::Value::Null)
    }

    fn into_bincode(&self) -> Vec<u8> {
        bincode::serialize(self)
            .inspect_err(|e| warn!("can not serialize for {:?}, cause: {}", self, e))
            .unwrap_or(Vec::default())
    }
}
